﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Web.Management;
using Top.Web;
using Top.Web.Api;
using Top.Core;
using Top.Data;
using Top.PointStore.Business;

namespace Top.PointStore.Business
{
    /*功能说明:商品展示操作管理类
    *版本:
    *参与人:王士锋
    *修改日期:2015.3.4
    */
    /// <summary>商品展示
    /// </summary>
    public class ProductShowManager
    {

        #region 基本方法

        /// <summary>根据用户ID得到一条记录
        /// </summary>
        /// <param name="productKid">用户ID</param>
        /// <returns></returns>
        public static async Task<T_ProductShow> Get(int productKid)
        {
            if (productKid <= 0) return new T_ProductShow();
            const string sql = @"select  * from T_ProductShow where F_ProductKid = {0} limit 1";
            using (var db = new DbTour())
            {
                return await db.Sql(sql, productKid).FirstOrDefault<T_ProductShow>();
            }
        }

        /// <summary> 增加一条数据
        /// <para>新增成功返回大于0</para>
        /// <para>0:兑换失败</para>
        /// <para>-1:商品id有误</para>
        /// <para>-2:兑换规则id有误</para>
        /// </summary>
        public static async Task<int> Add(T_ProductShow model)
        {
            if (model.F_ProductKid <= 0) return -1;
            if (model.F_ExchangeRuleKid <= 0) return -2;
            const string sql = @"insert into T_ProductShow 
                (
                    F_ProductKid,
                    F_ExchangeRuleKid,
                    F_ShowName,
                    F_Sort,
                    F_AddedTime,
                    F_SoldoutTime,
                    F_CreatedTime,
                    F_UpdatedTime,
                    F_Status,
                    F_IsDelete
                ) 
                values ({0:F_ProductKid},
                        {0:F_ExchangeRuleKid},
                        {0:F_ShowName},
                        {0:F_Sort},
                        {0:F_AddedTime},
                        {0:F_SoldoutTime},
                        now(),
                        now(),
                        {0:F_Status},
                        {0:F_IsDelete});
                select LAST_INSERT_ID()";

            using (var db = new DbTour())
            {
                return await db.Sql(sql, model).ExecuteScalar<int>();
            }
        }

        /// <summary>更新一条数据
        /// <para>更新成功返回大于0</para>
        /// <para>0:兑换失败</para>
        /// <para>-1:商品id有误</para>
        /// <para>-2:兑换规则id有误</para>
        /// </summary>
        public static async Task<int> Update(T_ProductShow model)
        {
            if (model.F_ProductKid <= 0) return -1;
            if (model.F_ExchangeRuleKid <= 0) return -2;
            const string sql = @"update T_ProductShow set 
                F_ProductKid={0:F_ProductKid},
                F_ExchangeRuleKid={0:F_ExchangeRuleKid},
                F_ShowName={0:F_ShowName},
                F_Sort={0:F_Sort},
                F_AddedTime={0:F_AddedTime},
                F_SoldoutTime={0:F_SoldoutTime},
                F_UpdatedTime=now(),
                F_Status={0:F_Status}
              where Kid={0:Kid}";

            using (var db = new DbTour())
            {
                return await db.Sql(sql, model).ExecuteNonQuery();
            }
        }

        public static async Task<int> UpdateByProductKid(T_ProductShow model)
        {
            if (model.F_ProductKid <= 0) return -1;
            if (model.F_ExchangeRuleKid <= 0) return -2;
            const string sql = @"update T_ProductShow set 
                F_ExchangeRuleKid={0:F_ExchangeRuleKid},
                F_ShowName={0:F_ShowName},
                F_Sort={0:F_Sort},
                F_AddedTime={0:F_AddedTime},
                F_SoldoutTime={0:F_SoldoutTime},
                F_UpdatedTime=now(),
                F_Status={0:F_Status}
              where F_ProductKid={0:F_ProductKid}";

            using (var db = new DbTour())
            {
                return await db.Sql(sql, model).ExecuteNonQuery();
            }
        }
        #endregion

        /// <summary>产品上架
        /// </summary>
        public static async Task<int> ProductAdded(int productKid)
        {
            if (productKid <= 0) return 0;            
            const string sql = @"update T_ProductShow set F_Status=1 where F_ProductKid={0}";
            int res = 0;
            using (var db = DataBaseContext.GetDataBase("write"))
            {
                res = await db.Sql(sql, productKid).ExecuteNonQuery();
            }
            await MemoryTable.Init_ProductShow_table();
            return res;
        }

        /// <summary>产品下架
        /// </summary>
        public static async Task<int> ProductSoldout(int productKid)
        {
            if (productKid <= 0) return 0;            
            const string sql = @"update T_ProductShow set F_Status=0 where F_ProductKid={0}";
            int res = 0;
            using (var db = DataBaseContext.GetDataBase("write"))
            {
                res= await db.Sql(sql, productKid).ExecuteNonQuery();
            }
            await MemoryTable.Init_ProductShow_table();
            return res;
        }

        /// <summary>产品重置
        /// </summary>
        public static async Task<int> ProductReset(int productKid)
        {            
            using (var db = DataBaseContext.GetDataBase("write"))
            {
                const string sql = @"
                        update T_ProductShow 
                        set
                            F_AddedTime={0:F_AddedTime},
                            F_SoldoutTime={0:F_SoldoutTime},
                            F_Status=1,
                            F_UpdatedTime={0:F_UpdatedTime}
                        where F_ProductKid={0:F_ProductKid}";
                int res = await db.Sql(sql, new
                {
                    F_AddedTime = DateTime.Now,
                    F_SoldoutTime = DateTime.Now.AddDays(7),
                    F_UpdatedTime = DateTime.Now,
                    F_ProductKid = productKid
                }).ExecuteNonQuery();
                await MemoryTable.Init_ProductShow_table();
                return res;
            }
        }

        /// <summary>根据产品编号修改产品上架、下架、失效
        /// </summary>
        /// <param name="productKid"></param>
        /// <returns></returns>
        public static async Task<int> ProductSoldoutAdded(int productKid)
        {
            if (productKid <= 0) return 0;
            var model = await Get(productKid);

            if (model.F_SoldoutTime < DateTime.Now)
            {
                return await ProductReset(productKid);
            }
            else if (model.F_Status == 1)
            {
                return await ProductSoldout(productKid);
            }
            else
            {
                return await ProductAdded(productKid);
            }

        }


        /// <summary>获取上架商品
        /// </summary>
        /// <param name="categoryKid">商品分类</param>
        /// <param name="stock">是否已售完:0、未售完，1、已售完</param>
        /// <param name="name">产品名称</param>
        /// <param name="pager"></param>
        /// <returns></returns>
        public static async Task<IList<T_ProductShowExpand>> GetSoldoutProductList(int cityKid, int authCityKid, int categoryKid, string stock, string name, Pager pager)
        {

            using (var db = new DbTour())
            {
                var query = db.Table(@"select * from V_ProductShowList");

                if (authCityKid != 0)
                {
                    query.And(" F_CityKid = {0}", authCityKid);
                }
                else
                {
                    if (cityKid > 0)
                    {
                        query.And(" F_CityKid = {0}", cityKid);
                    }
                }

                if (categoryKid > 0)
                {
                    query.And(" F_CategoryKid ={0}", categoryKid);
                }
                if (!string.IsNullOrEmpty(stock))
                {
                    if (int.Parse(stock) == 1)
                    {
                        query.And(" F_InventoryNum ={0}", 0);
                    }
                }
                if (!string.IsNullOrEmpty(name))
                {
                    query.And(" F_ProductName like {0}", "%" + name + "%");
                }

                var list = await query.ToList<T_ProductShowExpand>();

                //return list;

                foreach (var item in list)
                {
                    if (item.F_SoldoutTime < DateTime.Now)
                    {
                        if (item.F_Status == 2)
                        {
                            continue;
                        }
                        item.F_Status = 2;
                        item.IsButton = 2;
                        string sql2 = "update T_ProductShow set F_Status=2 where Kid={0}";
                        await db.Sql(sql2, item.Kid).ExecuteNonQuery();
                    }
                    else
                    {
                        switch (item.F_Status)
                        {
                            case 0:
                                item.IsButton = 0;
                                break;
                            case 1:
                                item.IsButton = 1;
                                break;
                            case 2:
                                item.IsButton = 2;
                                break;
                        }
                    }
                }

                var list2 = await query.ToList<T_ProductShowExpand>(pager.StartNumber, pager.EndNumber, " F_CreatedTime desc");
                foreach (var item in list2)
                {
                    switch (item.F_Status)
                    {
                        case 0:
                            item.IsButton = 0;
                            break;
                        case 1:
                            item.IsButton = 1;
                            break;
                        case 2:
                            item.IsButton = 2;
                            break;
                    }
                }
                return list2;

            }
        }


        /// <summary>获取已上架商品（包含：上架，下架，失效）
        /// </summary>
        /// <returns></returns>
        /// <param name="categoryKid">商品分类</param>
        /// <param name="status">展示状态:0、下架，1、上架，2、失效</param>
        /// <param name="keyWords">产品名称</param>
        /// <param name="pager"></param>
        public static async Task<PagedList<T_ProductShowExpand>> GetList(int cityKid, int categoryKid, string status, string keyWords, int authCityKid, Pager pager)
        {
            using (var db = DataBaseContext.GetDataBase("reader"))
            {
                var query = db.Table(@"select * from v_productwarehouse");
                if (!string.IsNullOrEmpty(status))
                {
                    query.And("F_Status={0}", status);
                }
                if (categoryKid > 0)
                {
                    query.And("F_CategoryKid = {0}", categoryKid);
                }

                if (authCityKid != 0)
                {
                    query.And(" F_CityKid = {0}", authCityKid);
                }
                else
                {
                    if (cityKid > 0)
                    {
                        query.And(" F_CityKid = {0}", cityKid);
                    }
                }
                if (!string.IsNullOrEmpty(keyWords))
                {
                    query.And("F_ProductName like '%" + keyWords + "%'");
                }
                var list = await query.ToList<T_ProductShowExpand>();

                foreach (var item in list)
                {
                    if (item.F_SoldoutTime < DateTime.Now)
                    {
                        if (item.F_Status == 2)
                        {
                            continue;
                        }
                        string sql2 = "update T_ProductShow set F_Status=2 where Kid={0}";
                        await db.Sql(sql2, item.Kid).ExecuteNonQuery();
                    }
                }

                var list2 = await query.ToPagedList<T_ProductShowExpand>(pager.StartNumber, pager.EndNumber, " F_CreatedTime desc");

                return list2;
            }
        }


        /// <summary>展示商品数据列表
        /// </summary>
        /// <returns></returns>
        public static async Task<IList<T_ProductShowExpand>> GetProductShow(int isMeskill, string cityName, Pager pager)
        {
            using (var db = new DbTour())
            {
                var cityId = 0;
                if (!string.IsNullOrEmpty(cityName))
                {
                    string sql = "select Kid from T_ProvinceCityArea where [F_Name] like {0} and F_ParentKid <>0 ";
                    cityId = await db.Sql(sql, "%" + cityName + "%").ExecuteScalar<int>(0);
                }
                if (cityId == 0) cityId = 112;
                var query = db.Table(@"select  distinct
                    a.*,b.F_ProductName,
                    b.F_CategoryKid,
                    b.F_PicUrl,
                    b.F_Description,
                    c.F_BeginTime,
                    c.F_EndTime,
                    c.F_PointNum,
                    c.F_IsMeskill,
                    c.F_ExchangeBeginTime,
                    c.F_ExchangeEndTime,
                    d.F_InventoryNum
                    from T_ProductShow a 
                    left join T_PointProduct b on a.F_ProductKid=b.Kid
                    left join T_ExchangeRule c on a.F_ExchangeRuleKid=c.Kid 
                    left join T_ProductInventory d on a.F_ProductKid=d.F_ProductKid
                    left join T_RuleToCity r on c.Kid=r.F_RuleKid");
                query.And("c.F_Disabled = 1 and  a.F_IsDelete = 0 and a.F_Status=1");
                query.And("a.F_AddedTime < now()");
                query.And("a.F_SoldoutTime > now()");
                query.And("d.F_InventoryNum > 0");
                if (cityId > 0)
                {
                    query.And("(r.F_CityKid={0} or r.F_CityKid is null)", cityId);
                }
                if (isMeskill >= 0)
                {
                    query.And("c.F_IsMeskill={0}", isMeskill);
                }
                var list = await query.ToList<T_ProductShowExpand>(pager.StartNumber, pager.EndNumber, "a.F_Sort asc");
                //foreach (var productShowExpand in list)
                //{
                //    productShowExpand.Thumbs = IOHelper.GetThumbList(productShowExpand.F_PicUrl);
                //}
                return list;
            }
        }

        public static IList<T_ProductShowExpandV3> GetProductShow(int isMeskill, int cityKid, Pager pager)
        {
            using (var db = new DbTour())
            {
                StringBuilder sql = new StringBuilder();
                sql.Append(@"
                    SELECT
	                    iFNULL(F_CityKid, 0) AS F_CityKid,
	                    Kid,
	                    F_Sort,
	                    F_ShowName,
	                    F_AddedTime,
	                    F_SoldoutTime,
	                    F_ProductKid,
	                    F_ProductName,
	                    F_PicUrl,
	                    F_BeginTime,
	                    F_EndTime,
	                    F_PointNum,
	                    F_IsMeskill,
	                    F_ExchangeBeginTime,
	                    F_ExchangeEndTime,
	                    F_InventoryNum,
	                    ExchangeNum
                    FROM
	                    V_ProductShow
                    where 1=1
                ");
                sql.Append(" and F_AddedTime<=now() and F_SoldoutTime>=now() ");
                if (cityKid > 0)
                {
                    sql.AppendFormat("and (F_CityKid={0} or F_CityKid is null)", cityKid);
                }
                if (isMeskill >= 0)
                {
                    sql.AppendFormat("and F_IsMeskill={0}", isMeskill);
                }
                try
                {
                    var list = db.Sql(sql.ToString()).ToList<T_ProductShowExpandV3>(pager.StartNumber, pager.EndNumber, "F_Sort asc").Result;
                    foreach (var item in list)
                    {
                        item.F_EndTime = item.F_EndTime.AddDays(-1);
                        item.F_SoldoutTime = item.F_EndTime.AddDays(-1);
                    }
                    return list;
                }
                catch (Exception ex)
                {
                    Trace.Write(ex, "获取商品展示列表");
                    return new List<T_ProductShowExpandV3>();
                }
            }
        }

        public static List<T_ProductShowExpandV3> GetProductShow_Memory(int isMeskill, int cityKid, Pager pager)
        {
            if (MemoryTable.TB_ProductShow.Count>0)
            {
                List<T_ProductShowExpandV3> list = new List<T_ProductShowExpandV3>();

                if (cityKid > 0)
                {
                    list = (
                            from productShow in MemoryTable.TB_ProductShow
                            where productShow.F_CityKid == cityKid || productShow.F_CityKid == 0
                            select productShow
                           ).ToList();
                }
                if (isMeskill >= 0)
                {
                    list = (
                            from productShow in MemoryTable.TB_ProductShow
                            where productShow.F_IsMeskill.Equals(isMeskill)
                            select productShow
                           ).ToList();
                }
                return list.Skip(pager.PageIndex * pager.PageSize).Take(pager.PageSize).ToList();
            }
            else
            {
                return GetProductShow(isMeskill, cityKid, pager).ToList<T_ProductShowExpandV3>();
            }            
        }

        /// <summary>得到一个实体
        /// </summary>
        public static async Task<T_ProductShowExpandV3> GetModel(int productKid, OAuthUser user)
        {
            if (productKid <= 0 || user == null || string.IsNullOrEmpty(user.UserToken.ToString())) return null;

            //判断商品是否存在
            int resultCount = await PointProductManager.IsExists(productKid);
            if (resultCount <= 0) return null;

            //判断经济人是否属于分销公司
            bool isDistribute = false;
            if (user != null)
            {
                isDistribute = await LoginManager.IsInDistribute(user);
            }

            using (var db = new DbTour())
            {
                const string sql = @"select a.*,b.F_ProductName,b.F_CategoryKid,b.F_PicUrl,b.F_Description,
c.F_BeginTime,c.F_EndTime,c.F_PointNum,c.F_Disabled,c.F_Status as F_ExchangeStatus,c.F_ExchangeType,c.F_UserExchangeNum,F_ExchangeNum,c.F_ExchangeBeginTime,c.F_ExchangeEndTime,c.F_IsExchange,c.F_IsMeskill,
d.F_InventoryNum,d.F_Source
                    from T_ProductShow a left join T_PointProduct b on a.F_ProductKid=b.Kid
                    left join T_ExchangeRule c on a.F_ExchangeRuleKid=c.Kid 
                    left join T_ProductInventory d on a.F_ProductKid=d.F_ProductKid 
                where a.F_ProductKid = {0}                     
";
                var model = await db.Sql(sql, productKid).FirstOrDefault<T_ProductShowExpandV3>();
                model.T_ProductPic = await ProductPicManager.GetList(productKid);
                //model.Thumbs = IOHelper.GetThumbList(model.F_PicUrl);

                if (isDistribute)
                {
                    model.F_PointNum = model.F_PointNum * 10;
                }
                var pointMain = await PointManager.Get(user.UserToken.ToString());
                if (pointMain == null)
                {
                    model.IsStutas = -3;//TODO:兑换规则id不返回
                }
                else
                {
                    model.IsStutas = await Checking(productKid, user, model, 1, pointMain.F_PointBalance);//TODO:兑换规则id不返回
                }
                return model;
            }
        }

        private static System.Collections.Concurrent.ConcurrentDictionary<Guid, int> IsUserBuying = new System.Collections.Concurrent.ConcurrentDictionary<Guid, int>(4 * Environment.ProcessorCount, 800);

        /// <summary> 购买商品
        /// <para>-1:活动未开启</para>
        /// <para>-2:超出活动时间范围</para>
        /// <para>-3:经纪人不存在</para>
        /// <para>-4:经纪人积分不足</para>
        /// <para>-5:库存不足</para>
        /// <para>-6:超出用户兑换数量</para>
        /// <para>-7:该商品当日兑换数量已满</para>
        /// <para>-8:兑换时间有误</para>
        /// <para>-9:未到商品兑换开始时间</para>
        /// <para>-10:商品兑换时间已结束</para>
        /// </summary>
        /// <param name="productKid"></param>
        /// <param name="broker"></param>
        /// <returns>大于0为兑换记录id,小于0为逻辑失败状态值,0为兑换失败</returns>
        public static async Task<int> Buy(int productKid, OAuthUser user)
        {
            if (productKid <= 0) return -11;
            if (user == null) return -3;

            var buy = await ProductShowManager.GetModel(productKid, user);
            if (buy == null) return -11;

            if (buy.F_Status != 1)
            {
                return -10;
            }

            var checkingRes = buy.IsStutas;
            if (checkingRes < 0) return checkingRes;

            if (!IsUserBuying.TryAdd(user.UserToken, 1))
            {
                return 0;
            }

            var exchangeKid = 0;
            using (var db = new DbTour())
            {
                //开启事务
                await db.Begin();
                try
                {
                    var pointMain = await PointManager.Get(user.UserToken.ToString());
                    if (pointMain == null) return -1;
                    if (pointMain.F_PointBalance<buy.F_PointNum)
                    {
                        return -4;
                    }

                    checkingRes = await Checking(productKid, user, buy, 2, pointMain.F_PointBalance);
                    if (checkingRes < 0)
                    {
                        db.Rollback();
                        return checkingRes;
                    }

                    //更新库存
                    int affectedRows = await PointProductManager.UpdateField(productKid, db);
                    if (affectedRows <= 0 || buy.F_InventoryNum <= 0)   //判断库存是否有存货    [商品已兑完]
                    {
                        db.Rollback();
                        return -5;
                    }
                    //插入兑换商品一条记录
                    var guid = Guid.NewGuid();

                    var productsexchange = new T_ProductsExchange_new()
                    {
                        F_UserToken = user.UserToken.ToString(),
                        F_ProductKid = buy.F_ProductKid,
                        F_ExchangeTime = DateTime.Now,
                        F_PointNum = buy.F_PointNum,
                        F_OrderNo = DateTime.Now.ToString("yyyyMMddHHmmfff"),
                        F_Guid = guid,
                        F_IsStatus = buy.F_ExchangeStatus == 1 ? (int)ExchangeState.Checking : (int)ExchangeState.Succeed, //7:审核中 1：兑换成功
                        F_ExchangeType = "积分兑换",
                        F_IsDisplay = 1
                    };
                    exchangeKid = await ProductsExchangeManager.Add(productsexchange, db);

                    #region 再次判断用户兑换次数

                    
                    //扣除积分
                    int pointRes = await PointManager.UpdateUserPoint(user.UserToken.ToString(), -buy.F_PointNum, "broker.point.cash", exchangeKid, "SUBTRACT", db);//积分兑换    
                    if (pointRes < 0)
                    {
                        db.Rollback();
                        return pointRes;
                    }

                    #endregion

                    db.Commit();
                }
                catch (Exception ex)
                {
                    Trace.Write(ex, "积分兑换商品异常");
                    db.Rollback();
                    return 0;
                }
                finally
                {
                    int value = 0;
                    if (!IsUserBuying.TryRemove(user.UserToken, out value))
                        IsUserBuying.TryRemove(user.UserToken, out value);
                }

            }
            if (MemoryTable.TB_ProductShow_Plus.ContainsKey(productKid))
            {
                MemoryTable.TB_ProductShow_Plus[productKid].ExchangeNum += 1;
                MemoryTable.TB_ProductShow_Plus[productKid].F_InventoryNum -= 1;
            }
            #region 提示城市管理员 对接oauth 用户基本信息待确定[各个系统]

            //bool isSendMsg = Top.Common.TopConfigHelper.GetAppSettings("IsSendMsg").To<bool>(false);
            //if (isSendMsg)
            //{
            //    if ((await GetCategoryName(product.F_CategoryKid)).Contains("实物"))
            //    {
            //        //当商品是实物时，微信提醒城市管理员处理
            //        var msgContent = string.Format("{0}{1}在积分商城兑换了{2},请及时处理", user.Name ?? user.NickName, user.Phone, buy.F_ProductName);

            //        var url = Configs.AppSettings["NewApiUrl"] + "/SysConfig/Message/SendBatchWeiXinServicMessage";

            //        Trace.Write(url + "?cityKid=" + broker.F_CityKid + "&msgContent=" + msgContent + "&msgType=PointExchange", "RemoteUrl");

            //        var stopwatch = new Stopwatch();
            //        stopwatch.Start();

            //        var data = await SimpleRequest.Get(url, new { cityKid = broker.F_CityKid, msgContent = msgContent, msgType = "PointExchange" });

            //        stopwatch.Stop();

            //        Trace.Write("远程接口执行完成 耗时:" + stopwatch.ElapsedMilliseconds + "ms", "RemoteServer");

            //        if (stopwatch.ElapsedMilliseconds > 100)
            //        {
            //            Trace.TraceWarning("调用远程服务器用时过长 " + stopwatch.ElapsedMilliseconds + "ms");
            //        }

            //        var res = Json.ToObject<JsonResult>(data);

            //        if ((bool)res.Data != true)
            //        {
            //            Trace.TraceError("调用外部接口微信通知管理员最新兑换消息失败！" + res.Message);
            //            return -4;
            //        }

            //        //当商品是实物时，微信提醒taojiali

            //        msgContent = string.Format("{0}{1}{2}在积分商城兑换了{3},请及时处理", user.F_CityName, user.Name ?? user.NickName, user.Phone, buy.F_ProductName);

            //        url = Configs.AppSettings["NewApiUrl"] + "/SysConfig/Message/SendWeixinServiceMessage";

            //        Trace.Write(url + "?weixinOpenID=" + Configs.AppSettings["AdministratorWeiXinID"] + "&msgContent=" + msgContent, "RemoteUrl");

            //        stopwatch.Reset();

            //        stopwatch.Start();

            //        data = await SimpleRequest.Get(url, new { weixinOpenID = Configs.AppSettings["AdministratorWeiXinID"], msgContent = msgContent });

            //        stopwatch.Stop();

            //        Trace.Write("远程接口执行完成 耗时:" + stopwatch.ElapsedMilliseconds + "ms", "RemoteServer");

            //        if (stopwatch.ElapsedMilliseconds > 100)
            //        {
            //            Trace.TraceWarning("调用远程服务器用时过长 " + stopwatch.ElapsedMilliseconds + "ms");
            //        }

            //        res = Json.ToObject<JsonResult>(data);

            //        if ((bool)res.Data != true)
            //        {
            //            Trace.TraceError("调用外部接口微信通知管理员最新兑换消息失败！" + res.Message);
            //            return -4;
            //        }
            //    }
            //}
            #endregion

            return exchangeKid;
        }



        public static async Task<int> Checking(int productKid, OAuthUser user, T_ProductShowExpandV3 buy, int position, int oldBalance = 0)
        {
            var now = DateTime.Now;

            //判断是否禁用兑换
            if (buy.F_Disabled == 0) return -1;//活动未开启

            //判断兑换规则时间范围
            if (buy.F_BeginTime > Convert.ToDateTime(now.ToString("yyyy-MM-dd"))) return -9;
            if (buy.F_EndTime < Convert.ToDateTime(now.ToString("yyyy-MM-dd"))) return -2;


            if (buy.F_Status != 1)
            {
                return -10;
            }

            //判断经纪人积分是否存在
            var pointMain = await PointManager.Get(user.UserToken.ToString());
            if (pointMain == null) return -3;
            //判断剩余积分是否具有购买能力
            if (oldBalance < buy.F_PointNum) return -4;

            //判断库存是否有存货    [商品已兑完]
            if (buy.F_InventoryNum <= 0) return -5;

            //// 兑换类型：0、永久，1、每天
            //rule.F_ExchangeType
            switch (buy.F_ExchangeType)
            {
                case 0://永久
                    var userExchangeNum = await ProductsExchangeManager.GetUserExchangeCount(user.UserToken.ToString(), productKid);
                    if ((position == 1 && userExchangeNum >= buy.F_UserExchangeNum) || (position == 2 && userExchangeNum > buy.F_UserExchangeNum))
                    {
                        return -6;//[已兑换]
                    }
                    break;
                case 1://每天
                    var userExchangeNumToday = await ProductsExchangeManager.GetUserExchangeCount(user.UserToken.ToString(), productKid, now.Date, now);
                    if ((position == 1 && userExchangeNumToday >= buy.F_UserExchangeNum) || (position == 2 && userExchangeNumToday > buy.F_UserExchangeNum))
                    {
                        return -6;//超出用户兑换数量 [商品已兑完]
                    }
                    break;
                default:
                    break;
            }


            //判断商品是否开启兑换限制
            if (buy.F_IsExchange == 1) //0关闭 1启用
            {
                //商品当日兑换数量
                var todayExchangeNum = await ProductsExchangeManager.GetListByProductKidCount(productKid, now.Date, now);

                if ((position == 1 && todayExchangeNum >= buy.F_ExchangeNum) || (position == 2 && todayExchangeNum > buy.F_ExchangeNum))
                    return -7;//该商品当日兑换数量已满   [商品已兑完]

                //商品每日兑换开始时间
                if (buy.F_ExchangeBeginTime == null) return -8;//兑换时间有误
                //商品每日兑换结束时间
                if (buy.F_ExchangeEndTime == null) return -8;//兑换时间有误


                //DateTime dtExchangeBeginTime = Convert3.To<DateTime>(buy.F_BeginTime.ToString("yyyy-MM-dd") + " " + buy.F_ExchangeBeginTime, now);
                //DateTime dtExchangeEndTime = Convert3.To<DateTime>(buy.F_EndTime.ToString("yyyy-MM-dd") + " " + buy.F_ExchangeEndTime, now);

                DateTime dtExchangeBeginTime = Convert3.To<DateTime>(now.Date.ToString("yyyy-MM-dd") + " " + buy.F_ExchangeBeginTime);
                DateTime dtExchangeEndTime = Convert3.To<DateTime>(now.Date.ToString("yyyy-MM-dd") + " " + buy.F_ExchangeEndTime);

                //if (!DateTime.TryParse(exchangeRule.F_BeginTime + " " + exchangeRule.F_ExchangeBeginTime,
                //    out  now))
                //    return -8;//兑换时间有误

                //if (!DateTime.TryParse(exchangeRule.F_EndTime + " " + exchangeRule.F_ExchangeEndTime,
                //    out now))
                //    return -8;//兑换时间有误

                if (now < dtExchangeBeginTime) return -9;//未到商品兑换开始时间
                if (now > dtExchangeEndTime) return -10;//商品兑换时间已结束

            }

            return 1;
        }

        /// <summary>根据商品分类编号获取商品分类名称
        /// </summary>
        /// <param name="kid"></param>
        /// <returns></returns>
        public static async Task<string> GetCategoryName(int kid)
        {
            const string sql = @"select F_CategoryName from T_ProductsCategory where Kid={0}";
            using (var db = new DbTour())
            {
                return await db.Sql(sql, kid).ExecuteScalar<string>("");
            }
        }




        /// <summary> 删除一条记录
        /// </summary>
        /// <param name="kid"></param>
        /// <returns></returns>
        public static async Task<int> Delete(int kid)
        {
            if (kid <= 0) return 0;
            const string sql = @"update T_ProductShow set F_DeletedTime={0:F_DeletedTime},F_IsDelete={0:F_IsDelete} where F_ProductKid = {0:Kid}";
            using (var db = new DbTour())
            {
                return await db.Sql(sql, new { F_DeletedTime = DateTime.Now, F_IsDelete = 1, Kid = kid }).ExecuteNonQuery();
            }
        }

        /// <summary>批量删除
        /// </summary>
        /// <param name="kids"></param>
        /// <returns></returns>
        public static async Task<int> DeleteList(string kids)
        {
            if (kids == "") return 0;
            string sql = string.Format(@"update T_ProductShow set F_DeletedTime = now(),F_IsDelete = 0 where F_ProductKid in ({0})", kids);
            using (var db = new DbTour())
            {
                return await db.Sql(sql).ExecuteNonQuery();
            }
        }
    }
}
